package com.gis3c.sys.security.shiro.token;

import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.commons.codec.binary.Base64;

public class DesEncrypt {
	private Key key;
	
	public DesEncrypt(String keyStr){
		setKey(keyStr);
	}
	public DesEncrypt(){
		setKey("123456789");
	}
	
	public String encrypt(String content){
		byte[] byteMi = null;  
        byte[] byteMing = null;  
        String strMi = ""; 
        
        try {  
            byteMing = content.getBytes("UTF8");  
            byteMi = this.getEncCode(byteMing);  
            strMi = Base64.encodeBase64String(byteMi);  
        } catch (Exception e) {  
            throw new RuntimeException(  
                    "Error initializing SqlMap class. Cause: " + e);  
        } finally {  
            byteMing = null;  
            byteMi = null;  
        }  
        return strMi;
        
	}
	private byte[] getEncCode(byte[] byteS) {  
        byte[] byteFina = null;  
        Cipher cipher;  
        try {  
            cipher = Cipher.getInstance("DES");  
            cipher.init(Cipher.ENCRYPT_MODE, key,SecureRandom.getInstance("SHA1PRNG"));  
            byteFina = cipher.doFinal(byteS);  
        } catch (Exception e) {  
            throw new RuntimeException(  
                    "Error initializing SqlMap class. Cause: " + e);  
        } finally {  
            cipher = null;  
        }  
        return byteFina;  
    }  
	
	private void setKey(String keyStr) {
		try{
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			this.key  = keyFactory.generateSecret(new DESKeySpec(keyStr.getBytes("UTF8")));
		}catch (Exception e) {  
			e.printStackTrace();
        }
	}
}
